package com.lancoo.answer.util;

import android.app.Activity;
import android.content.Context;
import android.os.IBinder;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SoftInputUtils {

    public static boolean shouldHideInput(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {
            int[] l = {0, 0};
            view.getLocationInWindow(l);
            int left = l[0];
            int top = l[1];

            int bottom = top + view.getHeight();
            int right = left + view.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * @param token
     * @param context
     */
    public static void hideSoftInput(IBinder token, Context context) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * @param mContext
     */
    public static void showSoftInput( Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm!=null){
            imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
        }
    }

    /**
     * 关闭软键盘
     * @param activity
     */
    public static void hideSoftInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    public static void setEditTextInputSpace( final EditText editText) {

        InputFilter filter = new InputFilter() {
            Pattern emoji = Pattern.compile(
                    "[^a-zA-Z0-9\\u4E00-\\u9FA5_,.?!:;…~_\\-\"\"/@*+'()<>{}/[/]()<>{}\\[\\]=%&$|\\/♀♂#¥£¢€\"^` ，。？！：；……～“”、“（）”、（——）‘’＠‘·’＆＊＃《》￥《〈〉》〈＄〉［］￡［］｛｝｛｝￠【】【】％〖〗〖〗／〔〕〔〕＼『』『』＾「」「」｜﹁﹂｀．✓√\n→∧—]",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Log.e("ee我-",""+source);
                Matcher emojiMatcher = emoji.matcher(source);
                if (emojiMatcher.find()){
                    Log.e("eee","");
                    return source.toString().replace(emojiMatcher.group(),"");
//                    HTextViewUtils.showToast(context,1,"禁止输入非法字符！");
//                    Toast.makeText(editText.getContext(),"禁止输入非法字符！", Toast.LENGTH_LONG).show();
//                    return "";//过滤掉匹配到的内容
                }else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter,new InputFilter.LengthFilter(10000)});
    }

    public static InputFilter getEmojiFilter() {
        return new InputFilter() {
            Pattern pattern = Pattern.compile(
                    "[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u2000-\u201f\r\n]",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE
            );

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = pattern.matcher(source);
                if (matcher.find()) return "";
                return null;
            }
        };
    }

    /**
     * 点击editText之外的区域隐藏软件盘，须在activity中dispatchTouchEvent方法中调用
     * @param ev
     * @param activity
     */
    public static void hideSoftInputOutSite(MotionEvent ev,Activity activity){
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = activity.getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken(),activity);
            }
        }

    }


    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = { 0, 0 };
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private static void hideSoftInput(IBinder token,Activity activity) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager)activity.
                    getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
